package utils;

import org.hibernate.Query;
import org.hibernate.Session;
import beans.AbstractPagedQuery;

/**
 * Dao工具类，提供一些常用的API.
 * @author spring
 */
public class DaoUtil {
    /**
     * 进行分页查询.
     * @param session hibernate session.
     * @param qc 分页查询对象
     */
    @SuppressWarnings("unchecked")
    public static void doPagedQuery(Session session, AbstractPagedQuery qc) {
        if (qc.getTotalCount() == -1) {// 查询总数

            Query query = qc.buildQuery(session, true);
            long totalCount = (Long) query.uniqueResult();
            qc.setTotalCount(totalCount);
        }
        // 查询细目
        qc.checkPagerOffset();
        Query query = qc.buildQuery(session, false);
        query.setFirstResult(qc.getPagerOffset());
        query.setMaxResults(qc.getItemsPerPage());
        // 设置查询结果集
        qc.setQueryResults(query.list());

    }
    
    /**
     * 获取可读的完整的异常信息
     * @param e 异常
     * @return 异常信息
     */
    public static String exceptionToStr(Throwable e)
    {
       StringBuilder sb=new  StringBuilder();
       String className=e.getClass().getName();
       int lastInx=className.lastIndexOf('.');
       if(lastInx>0)
       {
           className=className.substring(lastInx+1);
       }
       String msg=e.getLocalizedMessage();
       sb.append(className).append(":");
       if(msg!=null)
       {
           sb.append(msg);
       }
       Throwable cause=e.getCause();
       if(cause!=null)
       {
           sb.append(" caused by: ").append(exceptionToStr(cause));
       }
       return sb.toString();
       
    }
}
